// pages/batch/batch.js
var util = require('../../database/data.js');
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tid: '',
    cit: '',
    postOk: false,
    sms_num: 63,
    showDialog: false,
    showCenterDialog: true,
    canvasClose: true,
    showAlert: true,
    isShow: true,
    showLogin: true,
    sendOrder: false,
    disabled: false,
    alert_login_view: true
  },

  //弹窗
  onClickdiaCenterView: function(e) {
    this.setData({
      showCenterDialog: !this.data.showCenterDialog,
      showDialog: !this.data.showDialog
    })
  },

  //获取手机号注册
  getPhoneNumber: function(e) {
    let that = this;
    var sessionKey = that.data.sessionKey;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      wx.showLoading({
        title: '注册中',
      })
      wx.login({
        success: function(res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: app.globalData.smsbaoApi + '/batch/sapi/getOpenId',
              method: 'post',
              data: {
                code: res.code
              },
              success: function(res) {
                wx.request({
                  url: app.globalData.smsbaoApi + '/batch/sapi/decryptData',
                  method: "post",
                  data: {
                    sessionKey: res.data.data.session_key,
                    encryptedData: e.detail.encryptedData,
                    iv: e.detail.iv
                  },
                  header: {
                    'content-type': 'application/json'
                  },
                  success: function(res) {
                    wx.hideLoading()
                    that.setData({
                      phone: res.data.data,
                      alert_login_view: !that.data.alert_login_view
                    })

                  }
                })
              }
            })
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        }
      });

    } else {
      that.setData({
        showAlert: !that.data.showAlert
      })
      wx.showModal({
        title: '提示',
        content: '登陆短信宝账号即可发送',
        success: function(res) {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/info/info'
            })
          }
        }
      })
    }
  },
  smsUserPwdSubmit: function(e) {
    let that = this;
    var phone = JSON.parse(that.data.phone);
    if (e.detail.value.sms_register_pwd == '' || e.detail.value.sms_register_pwd == undefined) {
      wx.showToast({
        title: '密码不能为空',
        icon: 'none',
        duration: 2000
      })
    } else {
      that.setData({
        uphone: phone.phoneNumber,
        disabled: true
      })
      var smsData = {
        user: phone.phoneNumber,
        pwd: e.detail.value.sms_register_pwd,
        uPhone: phone.phoneNumber
      }
      var registerUrl = app.globalData.smsbaoApi + "/jwt/register.action?username=" + smsData.user + "&password=" + smsData.pwd + "&email=" + phone.phoneNumber + "@mobile.com" + "&qq=" + phone.phoneNumber + "&mobile=" + phone.phoneNumber;
      var header = {
        'content-type': 'application/json',
        'appId': app.globalData.appId,
        'appKey': app.globalData.appKey,
      }
      var method = 'POST';
      var i = 0;
      that.recursionRequest(registerUrl, '', method, header, smsData, i);
    }
  },
  //递归调用
  recursionRequest: function(url, data, method, header, smsData, i) {
    let that = this;
    if (i === 5 || that.data.postOK === true) {
      wx.showToast({
        title: '注册失败,联系客服',
        icon: 'none',
        duration: 2000
      })
      setTimeout(function() {
        wx.switchTab({
          url: '/pages/info/info'
        })
      }, 2500)
      return;
    } else {
      app.post(url, data, method, header).then((success_data) => {
        if (success_data.data.code == 200) {
          var info_url = app.globalData.smsbaoApi + "/jwt/member/info.action";
          var info_method = 'get';
          var info_header = {
            'content-type': 'application/json',
            'appId': app.globalData.appId,
            'appKey': app.globalData.appKey,
            "Authorization": success_data.header.token,
          }
          app.post(info_url, '', info_method, info_header).then((info_data) => {
            if (info_data.data.code == 200) {
              var smsUserInfo = {
                "userId": info_data.data.data.member.id,
                "username": info_data.data.data.member.username,
                "token": info_data.header.token,
                "balance": info_data.data.data.member.balance,
                "leaveCount": info_data.data.data.leaveCount,
              };
              wx.setStorageSync('smsInfo', smsUserInfo);
              wx.showToast({
                title: '注册成功',
                icon: 'loading',
                duration: 1000
              })
              setTimeout(function() {
                wx.switchTab({
                  url: '/pages/index/index'
                })
              }, 2000)
            } else {
              wx.showToast({
                title: info_data.data.desc,
                icon: 'none',
                duration: 1000
              })
            }
          })
          that.setData({
            postOk: true,
          })
        } else if (success_data.data.code == 400) {
          i++;
          var user = smsData.uPhone + "_" + i;
          var smsDataed = {
            user: user,
            pwd: smsData.pwd,
            uPhone: smsData.uPhone
          }
          var url = app.globalData.smsbaoApi + "/jwt/register.action?username=" + smsDataed.user + "&password=" + smsDataed.pwd + "&email=" + smsDataed.uPhone + "@mobile.com" + "&qq=" + smsDataed.uPhone + "&mobile=" + smsDataed.uPhone;
          this.recursionRequest(url, '', method, header, smsDataed, i);
        }
      })
    }

  },
  //获取用户信息
  userLoginSms: function(e) {
    let that = this;
    var phones = that.data.sendPhone;
    var phoneArr = phones.join(",");
    var content = that.data.upContent;
    var sign = that.data.signature;
    var classId = e.currentTarget.dataset.classid;
    var smsInfo = wx.getStorageSync('smsInfo');
    var size = Math.ceil((content.length + sign.length) / this.data.sms_num);
    if (smsInfo == '' || smsInfo == undefined) {
      that.setData({
        showAlert: !that.data.showAlert
      })
    } else {
      wx.request({
        url: app.globalData.smsbaoApi + "/jwt/member/sms/send_no_balance.action?phones=" + phoneArr + "&content=" + "【" + sign + "】" + content,
        method: 'post',
        header: {
          'content-type': 'application/json',
          'appId': app.globalData.appId,
          'appKey': app.globalData.appKey,
          'Authorization': smsInfo.token,
        },
        success: function(res) {
          if (res.data.code == 200) {
            var smsInfo = wx.getStorageSync('smsInfo');
            var smsUserInfo = {
              "userId": smsInfo.userId,
              "username": smsInfo.username,
              "token": res.header.token,
              "balance": smsInfo.balance,
              "leaveCount": smsInfo.leaveCount,
            };
            if (smsInfo.leaveCount <= 0) {
              wx.showModal({
                title: '提示',
                content: "短信已提交成功，您的余额不足以发送 " + size + " 条短信，请先充值后，我们的客服会将您的短信审核发送出去。",
                success: function(res) {
                  if (res.confirm) {
                    wx.redirectTo({
                      url: '/pages/info/recharge/recharge'
                    })
                  } else if (res.cancel) {
                    wx.redirectTo({
                      url: '/pages/info/logs/logs'
                    })
                  }
                }
              })
            } else {
              wx.showModal({
                title: '提示',
                content: "短信已提交成功,点击确定查看日志",
                success: function(res) {
                  if (res.confirm) {
                    wx.redirectTo({
                      url: '/pages/info/logs/logs'
                    })
                  } else if (res.cancel) {
                    that.setData({
                      showCenterDialog: !that.data.showCenterDialog,
                      showDialog: !that.data.showDialog
                    })
                  }
                }
              })

            }

            wx.setStorageSync('smsInfo', smsUserInfo);
            that.onBatchSubmit(classId, that.data.uphone);
          } else {
            wx.showToast({
              title: res.data.desc,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }

  },
  //数据提交
  onBatchSubmit: function(classId, contact) {
    var openId = wx.getStorageSync('openId');
    switch (classId) {
      case '0':
        var contData = this.data.contData;
        var api = app.globalData.smsbaoApi + '/batch/sapi/createOrder';
        var sendData = {
          appId: '10067',
          cid: contData.cid,
          tid: contData.tid,
          openId: openId.openId,
          contact: contact,
          sendPhone: JSON.stringify(this.data.sendPhone),
          sign: this.data.signature.replace(/(^\s*)|(\s*$)/g, ""),
          content: this.data.upContent,
        };
        console.log(sendData)
        this.submitSendData(api, sendData, openId.openId);
        break;
      case '1':
        var contData = this.data;
        var api = app.globalData.smsbaoApi + '/batch/sapi/createOrder';
        var sendData = {
          appId: '10067',
          cid: '0',
          tid: '0',
          openId: openId.openId,
          contact: contact,
          sendPhone: JSON.stringify(this.data.sendPhone),
          sign: this.data.signature.replace(/(^\s*)|(\s*$)/g, ""),
          content: this.data.upContent,
        };
        this.submitSendData(api, sendData, openId.openId);
        break;
    }

  },

  //发送短信到服务器
  submitSendData: function(url, data, openId) {
    let that = this;
    wx.request({
      url: url,
      method: "post",
      data: {
        appId: data.appId,
        cid: data.cid,
        tid: data.tid,
        openId: openId,
        contact: data.contact,
        phone: data.sendPhone,
        sign: data.sign,
        content: data.content
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        if (res.data.code == '200') {
          that.ProcessingReturnData(res, data);
          that.setData({
            orderId: res.data.data.orderId,
          })
        } else {
          wx.showToast({
            title: '网络超时',
            icon: 'loading',
            duration: 1500
          })
        }

      }
    })
  },
  //接受返回数据生成订单
  ProcessingReturnData: function(orderId, data) {
    let that = this;
    // 调用函数时，传入new Date()参数，返回值是日期和时间  
    var time = util.formatTime(new Date());
    var orderId = orderId.data.data.orderId;
    var orderData = wx.getStorageSync("order");
    var orderInfoData = [];
    for (var i in orderData) {
      orderInfoData.push(orderData[i])
    }
    var orderInfo = {
      orderId: orderId,
      tid: data.tid,
      cid: data.cid,
      phone: data.sendPhone,
      sign: that.data.signature,
      time: time,
      content: that.data.upContent
    };
    orderInfoData.push(orderInfo);
    wx.reportAnalytics('add_order', {
      add_order: orderId,
      add_time: time,
    });

    wx.setStorageSync('order', orderInfoData);
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    switch (options.class) {
      case '0':
        var contData = JSON.parse(options.data);
        var contents = contData.content;
        var start = contents.indexOf("【");
        var end = contents.indexOf("】");
        var sign = contents.substring(start + 1, end);
        var cont = contents.substring(end + 1);
        var signNum = sign.length + 2
        if (sign.length > 4) {
          var styleWeidth = 45;
        } else {
          var styleWeidth = 30;
        }
        //获取文本的数量
        var num = cont.length;
        var pag_num = Math.ceil(contents.length / this.data.sms_num);
        this.setData({
          contData: contData,
          cid: contData.cid,
          tid: contData.tid,
          styleWeidth: styleWeidth,
          sign: sign,
          signNum: signNum,
          content: cont,
          cont_num: num,
          page_num: pag_num,
          classId: options.class
        })
        break;
      case '1':
        //获取文本的数量
        var contData = JSON.parse(options.data);
        var start = contData.indexOf("【");
        var end = contData.indexOf("】");
        var sign = contData.substring(start + 1, end);
        var cont = contData.substring(end + 1);
        var signNum = sign.length + 2;
        var num = cont.length;
        var pag_num = Math.ceil(num / this.data.sms_num);
        if (sign.length > 4) {
          var styleWeidth = 45;
        } else {
          var styleWeidth = 30;
        }

        this.setData({
          sign: sign,
          styleWeidth: styleWeidth,
          content: cont,
          cont_num: num,
          signNum: signNum,
          page_num: pag_num,
          classId: options.class
        })
        break;
    }
    wx.hideNavigationBarLoading();
  },
  //短信内容的实时数量
  signNum: function(e) {
    var num = e.detail.value.length;
    this.setData({
      signNum: num + 2
    })
  },
  textNum: function(e) {
    var upd_num = e.detail.value.length;
    this.setData({
      cont_num: upd_num,
    })
  },
  //手机号验
  removeEmptyArrayEle: function(arr) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == undefined && arr[i] == null || arr[i] == "") {
        arr.splice(i, 1);
        i = i - 1; // i - 1 ,因为空元素在数组下标 2 位置，删除空之后，后面的元素要向前补位，
        // 这样才能真正去掉空元素,觉得这句可以删掉的连续为空试试，然后思考其中逻辑
      }
    }
    return arr;
  },
  //第一次提交
  onSubmit: function(e) {
    var smsInfo = wx.getStorageSync('smsInfo');
    if (smsInfo == '' || smsInfo == undefined) {
      this.setData({
        showLogin: !this.data.showLogin,
      })
    }
    if (e.type == 'submit') {
      var phone = e.detail.value.phone.split("\n");
      var phones = this.removeEmptyArrayEle(phone);
      var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (e.detail.value.phone == '') {
        wx.showToast({
          title: '请输入正确的手机号',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        return false;
      } else {
        for (var i = 0; i < phones.length; i++) {
          console.log(phone[i])
          if (!myreg.test(phones[i])) {
            wx.showToast({
              title: '手机号格式不正确',
              icon: 'none',
              duration: 2000,
              mask: true
            })
            return false;
          }
        }
        this.setData({
          sendPhone: phones
        })
      }
      if (e.detail.value.signature == '') {
        wx.showToast({
          title: '输入3-8个字符的短信签名',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        return false;
      };
      if (e.detail.value.content == '') {
        wx.showToast({
          title: '请输入短信内容',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        return false;
      };
      switch (e.detail.target.dataset.status) {
        case '1':
          this.setData({
            showCenterDialog: !this.data.showCenterDialog,
            showDialog: !this.data.showDialog,
            upContent: e.detail.value.content,
            signature: e.detail.value.signature,
            sendPhone: this.data.sendPhone,
            showLogin: !this.data.showLogin
          });
          break;
      }

    }
  },


})